<template>
  <el-dialog :title="userForm.userId?'修改信息':'添加信息'" :visible.sync="visible">
    <el-form :model="userForm" :rules="rules" label-width="80px" ref="userDom">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" :readonly="this.userForm.userId?true:false" placeholder="登录名"/>
      </el-form-item>
      <template v-if="!userForm.userId">
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" show-password placeholder="登录密码"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" show-password placeholder="确认密码"/>
        </el-form-item>
      </template>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="userForm.nickname" placeholder="显示名"/>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload :action="uploadUrl" :headers="uploadHeader" :limit="1" :list-type="'picture-card'" :before-upload="beforeUpload" :on-exceed="onExceed" :on-success="onSuccess" :file-list="fileList" ref="uploadImage">
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img :src="file.url" alt="" class="el-upload-list__item-thumbnail">
            <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img :src="dialogImgSrc" alt="" height="100%" width="100%">
        </el-dialog>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="userForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" @click="submitInfo">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const initInfo = {
  userId: '',
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  avatar: '',
  status: 1
}
export default {
  name: 'UserAddOrUpdate',
  data () {
    return {
      visible: false,
      userForm: {
        ...initInfo
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (!this.userForm.userId && !value) {
                callback(new Error('密码不能为空'))
              } else {
                callback()
              }
            },
            required: true,
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          {
            validator: (rule, value, callback) => {
              if (!this.userForm.userId && value !== this.userForm.password) {
                callback(new Error('两次密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        nickname: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ]
      },
      loading: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload',
      baseImageUrl: process.env.VUE_APP_BASE_API + '/img/',
      uploadHeader: {
        token: ''
      },
      dialogVisible: false,
      dialogImgSrc: '',
      fileList: []
    }
  },
  methods: {
    init (userId) {
      /* 开启弹窗 */
      this.visible = true
      this.userForm = { ...initInfo }
      /* 判断userId是否有值 */
      if (userId) {
        /* 成立表示该次操作为修改，发送ajax请求获取信息 */
        this.$http.get('/sys/user/info/' + userId).then(data => {
          if (data.code === 0) {
            this.userForm = {
              ...data.user
            }
            if (this.fileList.length > 0) {
              this.fileList.length = 0
            }
            this.fileList.push({ url: this.baseImageUrl + data.user.avatar })
          } else {
            this.$message.error('数据加载失败，请重试！')
          }
        })
      }
    },
    submitInfo () {
      this.$refs.userDom.validate(valid => {
        if (valid) {
          this.loading = this.$loading({ text: '加载中...' })
          this.$http.post('/sys/user/update', this.userForm).then(data => {
            this.loading.close()
            if (data.code === 0) {
              this.$message({
                message: `${!this.userForm.userId ? '添加' : '修改'}成功`,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('onCloseWin')
                }
              })
            } else {
              this.$alert('操作失败', { type: 'error' })
            }
          })
        }
      })
    },
    beforeUpload (file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isImg) {
        this.$message.error('文件格式不正确！')
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('文件大小不能超过5M')
      }
      return isImg && isLt5M
    },
    onExceed () {
      this.$message.error('请先删除已存在的图片')
    },
    onSuccess (res) {
      if (res.code === 0) {
        this.userForm.avatar = res.data
        if (this.fileList.length > 0) {
          this.fileList.length = 0
        }
        this.fileList.push({ url: this.baseImageUrl + res.data })
      } else {
        this.$message.error(res.msg)
      }
    },
    handlePictureCardPreview (file) {
      this.dialogVisible = true
      this.dialogImgSrc = file.url
    },
    handleRemove (file) {
      this.$confirm('确定删除该图片吗？').then(() => {
        this.userForm.avatar = ''
        this.$refs.uploadImage.handleRemove(file)
      })
    }
  },
  created () {
    this.uploadHeader.token = this.$cookies.get('token')
  }
}
</script>

<style scoped>

</style>
